<template>
  <div class="app-container">
    <el-form
      ref="listFilterRef"
      :model="list.filter"
      inline
      class="list-filter"
    >
      <el-form-item prop="areaCode">
        <RegionSelect v-model="list.filter.areaCode" />
      </el-form-item>
      <el-form-item prop="companyId">
        <KiSelect
          v-model="list.filter.companyId"
          placeholder="输入企业名称搜索"
          :search="
            companyName =>
              new Promise(resolve =>
                $POST('sot-admin-api/sys/company/listForSelect', {
                  companyName
                }).then(({ data }) => {
                  resolve(data)
                })
              )
          "
          :props="{ value: 'companyId', label: 'companyName' }"
        />
      </el-form-item>
      <el-form-item prop="scenicId">
        <KiSelect
          v-model="list.filter.scenicId"
          placeholder="输入景区名称搜索"
          :search="
            scenicName =>
              new Promise(resolve =>
                $POST('sot-admin-api/scenic/listForSelect', {
                  scenicName
                }).then(({ data }) => {
                  resolve(data)
                })
              )
          "
          :options.sync="options.scenic"
          :props="{ value: 'scenicId', label: 'scenicName' }"
        />
      </el-form-item>
      <el-form-item prop="scenicLevel">
        <KiSelect
          v-model="list.filter.scenicLevel"
          :options="dict.scenic_grade"
          placeholder="景区等级"
          @change="()=>{
            $set(list.filter,'scenicType',undefined)
          }"
        />
      </el-form-item>
      <el-form-item prop="scenicType">
        <KiSelect
          v-model="list.filter.scenicType"
          :options="dict.stadium_type"
          placeholder="场馆类型"
          @change="()=>{
            $set(list.filter,'scenicLevel',undefined)
          }"
        />
      </el-form-item>

      <el-form-item prop="status">
        <KiSelect
          :index.sync="list.filter.status"
          :options="['停用', '启用']"
          placeholder="状态"
        />
      </el-form-item>
      <el-button @click="reset">重置</el-button>
    </el-form>

    <div class="table-operation">
      <span>
        <el-button
          v-if="hasBtn['新增']"
          type="primary"
          icon="el-icon-circle-plus-outline"
          @click="c"
          class="!mr-8px"
        >
          新增
        </el-button>
        <ExportExcel url="/sot-admin-api/scenic/export" :param="list.filter" />
      </span>
      <el-pagination
        v-bind="elPaginationProps"
        :total="list.total"
        :currentPage.sync="list.filter.pageNo"
        :pageSize.sync="list.filter.pageSize"
      />
    </div>

    <el-table v-loading="list.loading" :data="list.data" v-bind="tableProp">
      <el-table-column label="景区ID" prop="scenicId" />
      <el-table-column label="景区名称" prop="scenicName" />
      <el-table-column label="企业名称" prop="companyName" />
      <el-table-column label="所属地区" prop="areaName" />
      <el-table-column label="地点" prop="address" />
      <el-table-column label="景区等级（场馆类型）" width="180">
        <template slot-scope="{ row }" >
          <span v-if="row.type=='01'">
            {{ row.scenicLevel | $value2label(dict.scenic_grade) }}
          </span>
          <span v-if="row.type=='02'">
            {{ row.scenicType | $value2label(dict.stadium_type) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="类型" prop="type">
        <template slot-scope="{ row }">
          {{
            type.filter(v => row.type === v.dataValue)[0] &&
              type.filter(v => row.type === v.dataValue)[0].dataName
          }}
        </template>
      </el-table-column>
      <el-table-column label="联系电话" prop="telephone" />
      <el-table-column label="开放时间">
        <template slot-scope="{ row }">
          {{
            row.openingTime && row.endingTime
              ? row.openingTime + ' - ' + row.endingTime
              : ''
          }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="{ row: { scenicId, status } }">
          <KiPopSwitch
            v-bind="popSwitchProps(status)"
            @change="updateStatus({ id: scenicId, status: status ^ 1 })"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="300">
        <template slot-scope="{ row }">
          <KiPopButton
            v-if="hasBtn['查看']"
            @click="r({ scenicId: row.scenicId })"
          >
            查看
          </KiPopButton>
          <KiPopButton
            v-if="hasBtn['编辑']"
            @click="u({ scenicId: row.scenicId })"
          >
            编辑
          </KiPopButton>
          <KiPopButton
            v-if="hasBtn['删除']" text="![#FF7575]"
            :elPopconfirmProps="{ title: '确认删除吗？' }"
            @click="d({ id: row.scenicId })"
          >
            删除
          </KiPopButton>
          <KiPopButton
            v-if="hasBtn['景区二维码']"
            @click="createQrCode(row)"
          >
            景区二维码
          </KiPopButton>
          <KiPopButton
            v-if="hasBtn['设置H5商城']"
            @click="showH5shop(row)"
          >
            设置H5商城
          </KiPopButton>
        </template>
      </el-table-column>
    </el-table>

    <KiFormDialog
      :show.sync="form.show"
      :title="formTitle"
      v-model="form.data"
      :submit="submitForm"
      :readonly="form.status === 'r'"
      ref="formRef"
      :loading="form.loading"
    >
      <template #el-form>
        <h2>基本信息</h2>
        <el-form-item label="企业" prop="__company" verify>
          <KiSelect
            v-model="form.data.__company"
            placeholder="输入企业名称搜索"
            :search="
              companyName =>
                new Promise(resolve =>
                  $POST('sot-admin-api/sys/company/listForSelect', {
                    companyName
                  }).then(({ data }) => {
                    resolve(data)
                  })
                )
            "
            value-key="companyId"
            :props="{ value: '', label: 'companyName' }"
            @change="changeCompany"
          />
        </el-form-item>
        <el-form-item label="类型" prop="type" verify>
          <KiSelect v-model="form.data.type" :options="type" />
        </el-form-item>
        <el-form-item
          label="景区名称"
          prop="scenicName"
          :verify="{ maxLength: 30 }"
        >
          <el-input
            v-model="form.data.scenicName"
            placeholder="请输入景区名称"
            clearable
          />
        </el-form-item>
        <el-form-item
          label="景区排序值"
          prop="sort"
          verify
        >
          <el-input-number v-model="form.data.sort" :step="1" :min="1" :max="1000000" step-strictly></el-input-number>
        </el-form-item>
        <el-form-item
          label="副标题"
          prop="subtitle"
          :verify="{ required: false, maxLength: 30 }"
        >
          <el-input
            v-model="form.data.subtitle"
            placeholder="请输入副标题"
            clearable
          />
        </el-form-item>
        <el-form-item label="景区等级" prop="scenicLevel" v-if="form.data.type=='01'">
          <KiSelect
            v-model="form.data.scenicLevel"
            :options="dict.scenic_grade"
            placeholder="请选择景区等级"
          />
        </el-form-item>
        <el-form-item label="场馆类型" prop="scenicType" v-if="form.data.type=='02'">
          <KiSelect
            v-model="form.data.scenicType"
            :options="dict.stadium_type"
            placeholder="请选择场馆类型"
          />
        </el-form-item>
        <el-form-item label="电话" prop="telephoneList" verify>
          <div v-for="(item, index) of form.data.telephoneList" :key="index">
            <div class="tel-row">
              <i
                class="el-icon-circle-close"
                @click="form.data.telephoneList.splice(index, 1)"
                v-show="form.status !== 'r' && form.data.telephoneList.length > 1"
              />
              <el-input
                v-model="form.data.telephoneList[index]"
                placeholder="请输入电话号码"
                show-word-limit
                maxlength="20"
              />
            </div>
          </div>
          <el-button
            v-show="form.data.telephoneList.length < 10"
            @click="form.data.telephoneList.push('')"
            icon="el-icon-plus"
            type="primary"
            plain
          />
        </el-form-item>
        <el-form-item label="开放月份" prop="openEndMonth" verify>
          <time-range-picker
            :start.sync="form.data.openStartMonth"
            :end.sync="form.data.openEndMonth"
            type="month"
          />
        </el-form-item>
        <el-form-item label="每日开放时间" prop="endingTime" verify>
          <TimeRangePicker
            type="time"
            :start.sync="form.data.openingTime"
            :end.sync="form.data.endingTime"
            value-format="HH:mm"
          />
        </el-form-item>
        <el-form-item label="交通情况" prop="traffic">
          <el-input
            type="textarea"
            :autosize="{ minRows: 3 }"
            placeholder="请输入交通情况"
            v-model="form.data.traffic"
            clearable
            show-word-limit
            maxlength="1000"
          ></el-input>
        </el-form-item>
        <el-form-item label="游览须知" prop="touristInformation">
          <el-input
            type="textarea"
            :autosize="{ minRows: 3 }"
            placeholder="请输入游览须知"
            v-model="form.data.touristInformation"
            clearable
            show-word-limit
            maxlength="3000"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="店铺"
          prop="relateShops"
          v-if="options.subMerchant && options.subMerchant.length > 0"
        >
          <KiSelect
            v-model="form.data.relateShops"
            :placeholder="form.data.__company ? undefined : '请先选择企业'"
            :options="options.subMerchant"
            :props="{ value: 'subMchId', label: 'name' }"
            multiple
          />
          <form-item-tip>
            多选，可选择同一企业下的所有店铺，选择后当前景区商城会展示所选店铺商品
          </form-item-tip>
        </el-form-item>
        <el-form-item label="选择贴图地图" prop="relateMaps">
          <KiSelect
            v-model="form.data.relateMaps"
            :options="options.map"
            :props="{ value: 'mapId', label: 'mapName' }"
            :placeholder="form.data.__company ? undefined : '请先选择企业'"
            multiple
          />
          <form-item-tip>
            多选，可选择同一企业下的所有贴图地图，选择后当前景区地图中会显示所选的全部贴图地图
          </form-item-tip>
        </el-form-item>
        <el-form-item label="地图显示其他景区点位" prop="relateScenics">
          <KiSelect
            v-model="form.data.relateScenics"
            multiple
            placeholder="输入景区名称搜索"
            :options.sync="companyScenics"
            :props="{ value: 'scenicId', label: 'scenicName' }"
          />
          <form-item-tip>
            多选，可选择同一企业下的其他景区，选择后当前景区地图中会显示所选景区点位
          </form-item-tip>
        </el-form-item>
        <el-form-item label="首页主题" prop="homeImage" verify>
          <Imgpond
            :count="1"
            v-model="form.data.homeImage"
            :size="1"
            :requestParam="{ original: true }"
          />
          <form-item-tip>建议图片尺寸：宽1000~2000，高1200</form-item-tip>
        </el-form-item>
        <el-form-item label="动态主题" prop="dynamicDisplay">
          <el-switch
            v-model="form.data.dynamicDisplay"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
          ></el-switch>
        </el-form-item>

        <h2>位置信息</h2>
        <el-form-item label="所属地区" prop="areaCode" verify>
          <RegionSelect
            v-model="form.data.areaCode"
            :label.sync="form.data.areaName"
            :props="{
              checkStrictly: true
            }"
          />
        </el-form-item>
        <CoordPicker
          :show.sync="showCoordPicker"
          :lng.sync="form.data.longitude"
          :lat.sync="form.data.latitude"
          :address.sync="form.data.address"
          :polygon.sync="form.data.__boundary"
          :polygonCount="1"
          :city="form.data.areaName"
        />
        <el-form-item label="所在位置" prop="address" :verify="{ maxLength: 45 }">
          <el-input
            v-model="form.data.address"
            placeholder="请打开地图选择位置"
            clearable
          >
            <el-button
              type="primary"
              slot="prepend"
              plain
              @click="showCoordPicker = true"
            >
              打开地图
            </el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="坐标" verify class="multiple">
          <el-form-item prop="longitude" :rules="rules.lng">
            <el-input
              v-model="form.data.longitude"
              placeholder="经度"
              clearable
            />
          </el-form-item>
          <el-form-item prop="latitude" :rules="rules.lat">
            <el-input
              v-model="form.data.latitude"
              placeholder="纬度"
              clearable
            />
          </el-form-item>
        </el-form-item>
        <el-form-item label="景区范围" prop="__boundary" verify>
          <el-tag
            effect="plain"
            type="success"
            v-if="form.data.__boundary && form.data.__boundary.length > 0"
          >
            已框选
          </el-tag>
          <el-tag effect="plain" type="warning" v-else-if="form.status !== 'r'">
            请打开地图框选景区范围
          </el-tag>
        </el-form-item>

        <h2>详细信息</h2>
        <el-form-item label="封面图片" prop="coverPath" verify>
          <Imgpond :count="1" v-model="form.data.coverPath" aspectRatio="1/1" />
        </el-form-item>
        <el-form-item label="详情图片" prop="detailPath" verify>
          <Imgpond
            :count="9"
            v-model="form.data.detailPath"
            valueType="array"
            aspectRatio="414/190"
          />
        </el-form-item>
        <el-form-item label="景区标签" prop="areaTag" verify>
          <DynamicTag
            v-model="form.data.areaTag"
            :count="4"
            :maxlength="9"
            v-if="form.show"
          />
        </el-form-item>
        <el-form-item label="景区简介" prop="description" verify>
          <el-input
            v-model="form.data.description"
            maxlength="30"
            show-word-limit
            clearable
            type="textarea"
            placeholder="请输入景区简介"
            :autosize="{ minRows: 2 }"
          />
        </el-form-item>
        <el-form-item label="详情" prop="introduction" verify>
          <MiniMCE v-model="form.data.introduction" :disabled="form.status === 'r'"/>
        </el-form-item>

        <h2>其他信息</h2>
        <el-form-item
          v-if="form.data.type === '02'"
          label="所属景区"
          prop="parentId"
        >
          <KiSelect
            v-model="form.data.parentId"
            placeholder="输入景区名称搜索"
            :options.sync="companyScenics"
            :props="{ value: 'scenicId', label: 'scenicName' }"
          />
        </el-form-item>
        <!-- <el-form-item label="景区热度" prop="hotRate" verify>
          <Sort
            v-model="form.data.hotRate"
            :max="9999"
            placeholder="请输入景区热度"
          />
        </el-form-item>
        <el-form-item label="是否网红景区" prop="popular">
          <el-switch
            v-model="form.data.popular"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
          />
        </el-form-item> -->
        <el-form-item label="三维地图链接" prop="threeMapUrl">
          <el-input
            v-model="form.data.threeMapUrl"
            maxlength="512"
            show-word-limit
            placeholder="请填写三维地图链接"
            clearable
          />
        </el-form-item>
        <!-- <el-form-item label="景区其他属性" prop="propTag">
          <KiSelect
            v-model="form.data.propTag"
            :options="dict.place_props"
            multiple
          />
        </el-form-item> -->
      </template>
    </KiFormDialog>

    <!-- 设置h5商城 -->
    <el-dialog :visible.sync="h5Shop.show" title="景区h5商城设置">
      <el-form
        ref="h5ShopForm"
        :model="h5Shop.data"
        label-width="120px"
        label-position="left"
        v-if="h5Shop.show"
      >
        <el-form-item label="景区名称" prop="__scenicName">
          <el-input v-model="h5Shop.data.__scenicName" disabled />
        </el-form-item>
        <el-form-item label="商城跳转界面" prop="status">
          <GlobalSearch
            v-if="h5Shop.show"
            v-model="h5Shop.data.sourceId"
            :type.sync="h5Shop.data.type"
            :sourceId.sync="h5Shop.data.sourceId"
            :sourceName.sync="h5Shop.data.sourceName"
          />
          <form-item-tip>
            这个设置主要用于设置H5商城；若设置了商城跳转页面，点击时跳转到对应页面；没有设置，则点击时跳转至原生景区商城。
          </form-item-tip>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="h5Shop.show = false">关 闭</el-button>
        <el-button
          type="primary"
          @click="submitH5Shop"
          :loading="h5Shop.loading"
        >
          保 存
        </el-button>
      </div>
    </el-dialog>

    <!-- 聚合码 -->
    <QrCodePreview ref="qrCode" />
  </div>
</template>

<script>
import { DynamicTag } from 'dynamic-tag'
import pageMixin from '@/utils/pageMixin'
import useAdmateAdapter from '@/utils/useAdmateAdapter'
import QrCodePreview from '@/components/QrCodePreview'
import ScenicChannel from './scenic-channel.vue'
import rules from '@/utils/rules'

export default {
  mixins: [pageMixin],
  components: { DynamicTag, ScenicChannel, QrCodePreview },
  setup: () =>
    useAdmateAdapter({
      urlPrefix: 'sot-admin-api/scenic',
      axiosConfig: {
        getList: {
          url: 'list'
        },
        r: {
          url: 'queryScenicInfoById'
        },
        d: {
          method: 'DELETE'
        }
      },
      form: {
        data: {
          telephoneList: [''],
          boundary: [],
          __boundary: [],
          __company: null,
          address: null,
          latitude: null,
          longitude: null,
          relateShops: []
        }
      }
    }, {
      afterRetrieve(res) {
        if (res.data.boundary?.length > 0) {
          this.form.data.__boundary = Array.from(res.data.boundary, v => {
            if (v?.data?.length > 0) {
              return {
                path: Array.from(v.data, v => ({
                  lng: v.longitude,
                  lat: v.latitude
                }))
              }
            }
          })
        }
        const { companyId, companyName, merchantId } = res.data
        this.form.data.__company = {
          companyId,
          companyName,
          merchantId
        }
        this.changeCompany(this.form.data.__company, true)
      },
      beforeSubmit() {
        this.form.data.telephoneList = this.form.data.telephoneList.filter(
          Boolean
        )
        if (this.form.data.__boundary.length > 0) {
          this.form.data.boundary = Array.from(this.form.data.__boundary, v => {
            if (v?.path?.length > 0) {
              return {
                data: Array.from(v.path, v => ({
                  longitude: v.lng,
                  latitude: v.lat
                }))
              }
            }
          })
        }
      },
    }),
  data () {
    return {
      rules,
      showCoordPicker: false,
      showDownLoad: false,
      type: [
        { dataValue: '01', dataName: '景区' },
        { dataValue: '02', dataName: '场馆' }
      ],
      place_props: [],
      companyScenics: [],
      options: {
        scenic: [],
        //mp: [],
        map: [],
        subMerchant: []
      },
      // 景区生态
      h5Shop: {
        show: false,
        loading: false,
        data: {
          id: '',
          __scenicName: '',
          __page: {}
        }
      }
    }
  },
  methods: {
    createQrCode (item) {
      this.$POST(
        '/sot-admin-api/reservation/reservation-info/queryForReservationId',
        {
          id: item.scenicId
        }
      ).then(res => {
        this.$refs.qrCode.show({
          title: item.scenicName + ' - 聚合码',
          text: `${import.meta.env.VITE_APP_QRCODE_URL}/scenicQRCode?id=${
            item.scenicId
          }&reservationId=${res.data.reservationId}`
        })
      })
    },
    changeCompany (e, isInit = false) {
      if (!isInit) {
        this.$set(this.form.data, 'relateShops', null)
        this.$set(this.form.data, 'appId', null)
        this.$set(this.form.data, 'relateMaps', null)
        this.$set(this.form.data, 'relateScenics', null)
      }
      if (!e) return
      this.form.data.companyId = e.companyId
      if (this.form.data.companyId) {
        this.options.subMerchant = []
        if (e.merchantId) {
          this.$POST('sot-admin-api/merchant/sub/queryListForNoPermission', {
            merchantId: e.merchantId
          }).then(res => {
            this.options.subMerchant = res.data
          })
        }

        this.$POST('sot-admin-api/scenic/map/listForSelect', {
          companyId: this.form.data.companyId,
          status: 1
        }).then(res => {
          this.options.map = res.data
        })

        // 获取企业下的景区
        this.$POST('sot-admin-api/scenic/listForSelect', {
          dataPermission: 0,
          companyId: this.form.data.companyId
        }).then(({ data }) => {
          this.companyScenics = data
        })
      } else {
        this.options.merchantId = []
        this.options.map = []
      }
    },
    // 提交h5商城设置
    submitH5Shop () {
      this.$refs.h5ShopForm.validate(_ => {
        if (_) {
          this.h5Shop.loading = true
          this.$POST('one-travel-api/scenic/settingH5Mall', this.h5Shop.data)
            .then(res => {
              if (res.errorCode == '00000') {
                this.$swal.success('提交成功')
                this.h5Shop.show = false
              } else {
                this.$swal.error(res.message)
              }
            })
            .finally(_ => {
              this.h5Shop.loading = false
            })
        }
      })
    },
    showH5shop (row) {
      // 获取已配置的信息
      this.$POST('one-travel-api/scenic/queryH5MallByScenicId', {
        id: row.scenicId
      }).then(res => {
        if (res.errorCode == '00000') {
          this.h5Shop.show = true
          this.h5Shop.data = res.data ? res.data : {}
          this.h5Shop.data.scenicId = row.scenicId
          this.h5Shop.data.__scenicName = row.scenicName
        } else {
          this.$swal.error(res.message)
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
h2:not(:first-child) {
  margin-top: 70px;
}

.el-icon-circle-check {
  color: green;
}

.tel-row {
  margin-bottom: 16px;
  position: relative;

  i {
    position: absolute;
    font-size: 32px;
    right: -40px;
    top: 2px;
    cursor: pointer;
    z-index: 1;
  }
}

:deep(.el-form-item.multiple) {
  & > .el-form-item__content {
    display: flex;
    justify-content: space-between;

    &:before,
    &:after {
      display: none;
    }

    .el-form-item {
      flex: 1;

      &:first-of-type {
        margin: 0 16px 0 0;
      }
    }
  }
}

.jh-qrcode {
  text-align: center;

  .qrcode {
    display: inline-block;
  }
}
</style>
